package dao;

import interfaceDAO.IDAOPreference;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import domain.HibernateUtil;
import domain.Preference;
import domain.User;

public class DAOPreference implements IDAOPreference {

	public Preference addPreference(User user, String alias, String address,
			double latitudeAddess, double longitudeAddess) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		try {

			Preference newPref = new Preference();

			newPref.setAlias(alias);
			newPref.setAddress(address);
			newPref.setLatitudeAddess(latitudeAddess);
			newPref.setLongitudeAddess(longitudeAddess);
			newPref.setUser(user);

			session.save(newPref);
			session.getTransaction().commit();

			return newPref;
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

	public Preference getPreference(User user, String alias) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		try {
			Criteria criteria = session.createCriteria(Preference.class);
			criteria.add(Restrictions.eq("user", user)).add(
				Restrictions.eq("alias", alias));
			List<?> preferences = criteria.list();
			if (preferences != null && !preferences.isEmpty()) {
				return (Preference) preferences.get(0);
			} else {
				return null;
			}
		} finally {
			HibernateUtil.closeSession(session);
		}

	}

	public int deletePreference(User user, String alias) {
		int success = -1;
		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		try {

			Preference pref = getPreference(user, alias);
			if (pref != null) {
				session.delete(pref);
				session.getTransaction().commit();
				success = 1;
			}
			return success;
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

	public Preference modifyPreference(User user, String alias, String address,
			double latitudeAddess, double longitudeAddess) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();
		try {
			Preference pref = getPreference(user, alias);
			if (pref != null) {
				pref.setAddress(address);
				pref.setLatitudeAddess(latitudeAddess);
				pref.setLongitudeAddess(longitudeAddess);

				session.update(pref);
				session.getTransaction().commit();

				pref = getPreference(user, alias);
				return pref;
			} else {
				return null;
			}
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

}